package com.blog.controller;


import com.blog.entity.Filter;
import com.blog.service.FileService;
import com.blog.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author blog
 * @since 2021-04-22
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }


    @GetMapping("/download")
    public String  download(@RequestParam("/fileName") String fileName) {

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream outputStream = null;
        try {
//            outputStream = response.getOutputStream();
            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File("D:/upload/" + fileName )));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "employee/EmployeeDownloadFile";
    }

    @PostMapping("/list")
    public Map getFilterList(@RequestBody Filter filter){
        return Result.ok(fileService.getPageFilterList(filter));
    }

    @DeleteMapping("/delete")
    public Result delete(String imgUrl){
        fileService.delete(imgUrl);
        return Result.ok();
    }
}

